package com.bawei.lib_common.base

import android.app.Application
import android.content.Context
import android.util.Log
import cn.jiguang.api.utils.JCollectionAuth
import cn.jiguang.verifysdk.api.JVerificationInterface
import cn.jpush.android.api.JPushInterface
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.manager.GlobalDataManager
import com.bawei.lib_common.utils.StartupOptimizer
import com.bawei.lib_storage.database.DBUtils
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMOptions
import com.qiniu.pili.droid.shortvideo.PLShortVideoEnv
import com.tencent.android.tpush.XGIOperateCallback
import com.tencent.android.tpush.XGPushConfig
import com.tencent.android.tpush.XGPushManager
import com.tencent.mmkv.MMKV
import com.tencent.rtmp.TXLiveBase
import com.tencent.rtmp.TXLiveBaseListener
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import com.umeng.qq.tencent.Tencent
import com.umeng.socialize.PlatformConfig
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


abstract class BaseApplication : Application() {
    companion object {
        lateinit var instance: BaseApplication
        private const val TAG = "BaseApplication"
    }

    private val initScope = CoroutineScope(Dispatchers.IO + SupervisorJob())

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        // 记录应用启动开始时间
        StartupOptimizer.startRecord()
    }

    override fun onCreate() {
        super.onCreate()
        instance = this


        StartupOptimizer.recordStage("Application.onCreate开始")

        // 关键组件初始化
        StartupOptimizer.recordStage("开始关键组件初始化")
        initCriticalComponents()
        StartupOptimizer.recordStage("关键组件初始化完成")

        // 延迟后台初始化，进一步减少延迟时间
        lifecycleScope.launch {
            delay(500) // 减少延迟到500ms
            StartupOptimizer.recordStage("开始后台组件初始化")
            initBackgroundComponents()
            StartupOptimizer.recordStage("后台组件初始化完成")
        }

        StartupOptimizer.recordStage("Application.onCreate完成")
    }

    /**
     * 关键组件初始化 - 必须立即初始化的组件
     */
    private fun initCriticalComponents() {
        // 只初始化最关键的组件
        MMKV.initialize(this)

        // ARouter初始化 - 必须在使用前初始化
        ARouter.openLog()
        ARouter.openDebug()
        ARouter.init(this)

        // 数据库初始化 - 必须在使用前初始化
        DBUtils.init(this, "IVideo.db")

        // 友盟统计初始化 - 简化配置
        UMConfigure.preInit(this, "686379d3bc47b67d839d0943", "channel")
        UMConfigure.setLogEnabled(false) // 关闭日志
        UMConfigure.init(
            this,
            "686379d3bc47b67d839d0943",
            "channel",
            UMConfigure.DEVICE_TYPE_PHONE,
            null
        )
        // QQ设置
        PlatformConfig.setQQZone("102799608", "5d63ae8858f1caab67715ccd6c18d7a5");

        // 简化MobclickAgent配置
        MobclickAgent.setCatchUncaughtExceptions(false) // 关闭异常捕获
        MobclickAgent.setSessionContinueMillis(30000)
        Tencent.createInstance("f140944f2db8c7a07419232ef613b1b4", applicationContext)


    }


    /**
     * 后台组件初始化 - 可以延迟初始化的组件
     */
    private suspend fun initBackgroundComponents() {
        withContext(Dispatchers.IO) {
            try {
                // 友盟统计的异步初始化
                initUmeng()
                //腾讯云初始化
                initTencent()
                //七牛云初始化
                initQiu()
                //极光初始化
                initJPush()
                // 其他非关键初始化
                initOtherComponents()
            } catch (e: Exception) {
                // 后台初始化失败不影响启动
            }
        }

        // 环信初始化必须在主线程中进行
        withContext(Dispatchers.Main) {
            try {
                initHyphenate()
            } catch (e: Exception) {
                Log.e(TAG, "环信初始化失败: ${e.message}")
            }
        }
    }

    private fun initJPush() {
        try {
            //极光初始化
            JCollectionAuth.setAuth(this, true)
            JPushInterface.setDebugMode(true)//BuildConfig.Debug
            JPushInterface.init(this)

            // 初始化一键登录，避免网络问题
            try {
                JVerificationInterface.setDebugMode(true)
                JVerificationInterface.init(this@BaseApplication) { code, result ->
                    Log.d("MyApp", "[init] code = $code result = $result")
                    when (code) {
                        8000 -> Log.d("MyApp", "极光一键登录初始化成功")
                        8004 -> Log.e("MyApp", "极光一键登录初始化失败: 网络或配置问题")
                        else -> Log.e("MyApp", "极光一键登录初始化失败: code=$code, result=$result")
                    }
                }
            } catch (e: Exception) {
                Log.e("MyApp", "极光一键登录初始化异常: ${e.message}")
            }

        } catch (e: Exception) {
            Log.e("MyApp", "极光推送初始化异常: ${e.message}")
        }
    }

    private fun initQiu() {

        PLShortVideoEnv.init(getApplicationContext());
    }

    private fun initHyphenate() {
        try {
            Log.d(TAG, "开始初始化环信SDK")
            val options = EMOptions()
            options.setAppKey("1111241028153227#ivideo")

            EMClient.getInstance().init(applicationContext, options)
            Log.d(TAG, "环信SDK初始化成功")
        } catch (e: Exception) {
            Log.e(TAG, "环信SDK初始化失败: ${e.message}")
            e.printStackTrace()
        }
    }

    private fun isMainProcess(): Boolean {
        val pid = android.os.Process.myPid()
        val am = getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
        val processName = am.runningAppProcesses?.firstOrNull { it.pid == pid }?.processName
        return processName == packageName
    }

    private fun initTencent() {
        Log.d(TAG, "当前包名: " + applicationContext.packageName)
        if (!isMainProcess()) {
            Log.d(TAG, "非主进程，不初始化TPNS")
            return
        }
        val licenceURL =
            "https://license.vod2.myqcloud.com/license/v2/1332570967_1/v_cube.license" // 获取到的 licence url
        val licenceKey = "3361e8787fd12ca7d3beb2b4152e6aeb" // 获取到的 licence key
        TXLiveBase.getInstance().setLicence(this, licenceURL, licenceKey)
        TXLiveBase.setListener(object : TXLiveBaseListener() {
            override fun onLicenceLoaded(result: Int, reason: String) {
                Log.i(TAG, "onLicenceLoaded: result:$result, reason:$reason")
            }
        })

        //fixTPushSharedPreferences();
        XGPushConfig.enableDebug(this, true)
        Log.d(TAG, "开始注册推送")
        XGPushManager.registerPush(this, object : XGIOperateCallback {
            override fun onSuccess(data: Any?, flag: Int) {
                Log.d(TAG, "注册成功，设备token为：$data")
                System.out.println("注册成功，设备token为：$data")
            }
            override fun onFail(data: Any?, errCode: Int, msg: String?) {
                Log.d(TAG, "onFail: 错误码：$errCode ，错误信息：$msg")
                System.out.println("onFail: 错误码：$errCode ，错误信息：$msg")
            }
        })
    }



    /**
     * 友盟统计异步初始化
     */
    private suspend fun initUmeng() {
        withContext(Dispatchers.IO) {
            // 最小化友盟初始化
            MobclickAgent.setScenarioType(
                this@BaseApplication,
                MobclickAgent.EScenarioType.E_UM_NORMAL
            )
        }
    }

    /**
     * 其他组件初始化
     */
    private suspend fun initOtherComponents() {
        withContext(Dispatchers.IO) {
            // 可以在这里添加其他非关键的初始化
            // 但要注意不要添加耗时的操作

            // 初始化购物车和收藏数量（延迟初始化，避免影响启动速度）
            initCartAndCollectCount()
        }
    }

    /**
     * 初始化购物车和收藏数量
     */
    private suspend fun initCartAndCollectCount() {
        try {
            // 这里可以调用网络请求获取初始数据
            // 但由于这是跨模块的，我们暂时设置为0，让具体的页面去获取
            GlobalDataManager.updateCartCount(0)
            GlobalDataManager.updateCollectCount(0)
        } catch (e: Exception) {
            Log.e(TAG, "初始化购物车和收藏数量失败: ${e.message}")
        }
    }

    /**
     * 获取协程作用域
     */
    private val lifecycleScope = CoroutineScope(Dispatchers.Main + SupervisorJob())

    override fun onTerminate() {
        super.onTerminate()
        // 应用退出时清理环信登录
        try {
            if (EMClient.getInstance().isLoggedInBefore) {
                EMClient.getInstance().logout(true, object : EMCallBack {
                    override fun onSuccess() {
                        Log.d(TAG, "应用退出时环信登出成功")
                    }

                    override fun onError(code: Int, error: String?) {
                        Log.e(TAG, "应用退出时环信登出失败: $error")
                    }

                    override fun onProgress(progress: Int, status: String?) {}
                })
            }
        } catch (e: Exception) {
            Log.e(TAG, "应用退出时环信登出异常: ${e.message}")
        }

        initScope.cancel()
        lifecycleScope.cancel()
    }
}
